/*
 * @(#)VandaSqlDateConverter.java 1.0 2005-4-7
 * Copyright 2005 VandaGroup, Inc. All rights reserved.
 */
package com.vanda.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
/**
 * 类说明:
 * 用于 VandaBeanUtils 的 java.sql.Date 转换器，将其他类型的值转换为 java.sql.Date 的值。
 * @author wkf3915
 * @version 1.0 2005-4-7
 */
public class VandaSqlDateConverter implements Converter {
	private Object defaultValue;
	private boolean useDefault;
	public VandaSqlDateConverter() {
		defaultValue = null;
		useDefault = false;
	}
	public VandaSqlDateConverter(Object defaultValue) {
		this.defaultValue = defaultValue;
		useDefault = true;
	}
	public Object convert(Class type, Object value) {
		try {
			if (value == null) {
				if (useDefault)
					return defaultValue;
				else
					throw new ConversionException("No value specified");
			}
			if (value instanceof java.sql.Date) {
				return value;
			}
			if (value instanceof java.util.Date) {
				return new java.sql.Date(((java.util.Date) value).getTime());
			}
			if (value instanceof String) {
				SimpleDateFormat formatter =
					new SimpleDateFormat(Globals.DATE_PATTERN);
				formatter.setLenient(false);
				try {
					java.util.Date dateValue = formatter.parse((String) value);
					if (dateValue != null) {
						return new java.sql.Date(dateValue.getTime());
					}
				} catch (ParseException e) {
				}
			}
			return java.sql.Date.valueOf(value.toString());
		} catch (Exception e) {
			if (useDefault)
				return defaultValue;
			else
				throw new ConversionException(e);
		}
	}
}
